package com.sum.tea.xinlian.viewmodel

import android.content.Intent
import android.os.Handler
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.function.commfun
import com.sum.tea.contants.AppConfig
import com.sum.tea.xinlian.Sub4TabActivity
import com.sum.tea.xinlian.bean.Constants
import com.sum.tea.xinlian.bean.ReadState
import com.sum.tea.xinlian.bean.TagInfo
import com.sum.tea.xinlian.utils.TagUtils
import com.tools.DjxlExcel
import com.uhf.api.cls.ErrInfo
import com.uhf.api.cls.ReadExceptionListener
import com.uhf.api.cls.ReadListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import com.uhf.api.cls.Reader
import com.uhf.api.cls.Reader.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import kotlin.math.abs

class MainViewModel(var myapp: AppConfig) : ViewModel() {

    // State管理
    private val _readState = MutableLiveData<ReadState>(ReadState.Stopped)
    val readState: LiveData<ReadState> get() = _readState

    private val _errorState = MutableLiveData<String>()
    val errorState: LiveData<String> get() = _errorState

    private val _tagCount = MutableLiveData(0)
    val tagCount: LiveData<Int> get() = _tagCount

    private val _totalCount = MutableLiveData(0)
    val totalCount: LiveData<Int> get() = _totalCount

    private val _runtime = MutableLiveData(0L)
    val runtime: LiveData<Long> get() = _runtime

    // 数据存储
    private val _tagsMap = MutableLiveData<Map<String, Reader.TAGINFO>>(emptyMap())
    val tagsMap: LiveData<Map<String, TAGINFO>> get() = _tagsMap

    private val _listMs = MutableLiveData<List<Map<String, String>>>(emptyList())
    val listMs: LiveData<List<Map<String, String>>> get() = _listMs

    private val _eantCount = MutableLiveData<Map<Int, List<String>>>(emptyMap())
    val eantCount: LiveData<Map<Int, List<String>>> get() = _eantCount

    // 事件流
    private val _soundEvent = MutableLiveData<Unit>()
    val soundEvent: LiveData<Unit> get() = _soundEvent

    private val _broadcastEvent = MutableLiveData<Intent>()
    val broadcastEvent: LiveData<Intent> get() = _broadcastEvent

    // 在启动读取时添加监听器
    private fun setupReaderListeners() {
        if (myapp.needlisen) {
            myapp.Mreader.apply {
                addReadListener(readListener)
                addReadExceptionListener(readExceptionListener)
            }
            myapp.needlisen = false
        }
    }

    // 内部状态和计数器
    var startTick = 0L
        private set
    private var vstaticStartTick = 0L
    private var totalCountLast = 0
    private var testCount = 0
    private var vmaxStaticCount = 0
    private var vallcount = 0f
    private var valltime = 0L
    private var allrdcnt = 0
    private var avgcnt = 0
    private var staticeveryt = 1000

    // 运行控制
    private var isRun = false
    private var isdroppow = false
    private var powstatus = true

    // 标签搜索相关
    private var tagdisIsFound = false
    private var tagdisAllRssi = 0
    private var tagdisAllCount = 0
    private val tagdisSoundCycle = 100

    // 统计相关
    private val vstaticTags = mutableListOf<String>()
    val gpodemoauthortags = mutableListOf<String>()

    // Excel导出
    private var dexel: DjxlExcel? = null

    // 协程和锁
    private val readScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    private val lockObj = Mutex()
    private val lockTagsm = Mutex()

    // Handler for UI updates
    var handler: Handler? = null

    init {
        resetCounters()
    }

    fun updateConfig(app: AppConfig){
        myapp = app
    }

    // 主要功能：开始读取
    fun startReading(
        onSound: () -> Unit,
        onUpdateUI: () -> Unit
    ) = viewModelScope.launch {
        try {
            if (!initializeReading()) {
                return@launch
            }

            startReadingProcess(onSound, onUpdateUI)

        } catch (e: Exception) {
            _errorState.postValue("读取错误: ${e.message}")
            stopReading()
        }
    }

    private suspend fun initializeReading(): Boolean {
        // 重置状态
        clearInternalStates()
        startTick = System.currentTimeMillis()

        // 初始化天线计数
        initializeAntCount()

        // 初始化报表
        if (myapp.isReport_rec) {
            initializeRecordReport()
        }
        if (myapp.isReport_tep) {
            initializeTemperatureReport()
        }

        // 设置盘点模式
        if (!selectInventoryMode()) {
            return false
        }

        isRun = true
        _readState.postValue(ReadState.Reading)
        return true
    }

    private suspend fun startReadingProcess(
        onSound: () -> Unit,
        onUpdateUI: () -> Unit
    ) {
        // 启动统计线程
        val statisticsJob = if (myapp.VisStatics) {
            launchStatisticsJob()
        } else null

        // 启动标签搜索线程
        val searchJob = if (myapp.isFoundTag) {
            launchTagSearchJob()
        } else null

        try {
            while (isRun) {
                val tagcnt = IntArray(1)
                val er = readTags(tagcnt)

                if (!processReadResult(er, tagcnt[0], onSound)) {
                    break
                }

                onUpdateUI()
                delay(myapp.Rparams.sleep.toLong())

                if (myapp.isswtichu8) {
                    switchU8Mode()
                }
            }
        } finally {
            statisticsJob?.cancel()
            searchJob?.cancel()
        }
    }

    private fun readTags(tagcnt: IntArray): Reader.READER_ERR {
        return if (myapp.isquicklymode) {
            myapp.Mreader.AsyncGetTagCount(tagcnt)
        } else {
            myapp.Mreader.TagInventory_Raw(
                myapp.Rparams.uants,
                myapp.Rparams.uants.size,
                myapp.Rparams.readtime.toShort(),
                tagcnt
            )
        }
    }

    private suspend fun processReadResult(
        er: Reader.READER_ERR,
        tagCount: Int,
        onSound: () -> Unit
    ): Boolean {
        return when (er) {
            Reader.READER_ERR.MT_OK_ERR -> {
                if (tagCount > 0) {
                    _tagCount.postValue(tagCount)
                    if (myapp.issound) onSound()

                    processTagData(tagCount)
                    true
                } else {
                    true
                }
            }
            else -> {
                handleError(er)
                false
            }
        }
    }

    // 标签读取监听器
    val readListener = ReadListener { _, tags ->
        viewModelScope.launch {
            // 播放提示音
            if (myapp.issound) {
                _soundEvent.postValue(Unit) // 触发声音事件，让Activity处理声音播放
            }

            // 处理每个读取到的标签
            tags.forEach { tag ->
                // 创建广播Intent
                Intent().apply {
                    action = Constants.BROADCAST_ACTION1
                    putExtra("ANT", tag.AntennaID)
                    putExtra("CRC", tag.CRC)
                    putExtra("EMD", tag.EmbededData)
                    putExtra("EML", tag.EmbededDatalen)
                    putExtra("EPC", tag.EpcId)
                    putExtra("EPL", tag.Epclen)
                    putExtra("FRQ", tag.Frequency)
                    putExtra("PC", tag.PC)
                    putExtra("PHA", tag.Phase)
                    putExtra("RDC", tag.ReadCnt)
                    putExtra("RES", tag.Res)
                    putExtra("RSI", tag.RSSI)
                    putExtra("TSP", tag.TimeStamp)
                }.let {
                    _broadcastEvent.postValue(it)
                }
            }
        }
    }

    // 异常监听器
    val readExceptionListener = ReadExceptionListener { _, re ->
        viewModelScope.launch {
            val errorMessage = buildString {
                append(re.toString())

                // 获取详细错误信息
                val errorInfo = ErrInfo()
                myapp.Mreader.GetLastDetailError(errorInfo)
                append(" ")
                append(testCount)
                append(errorInfo.errstr)
            }

            _errorState.postValue(errorMessage)

            // 如果是严重错误，停止读取
            if (re == Reader.READER_ERR.MT_HARDWARE_ALERT_ERR_BY_TOO_MANY_RESET) {
                myapp.needreconnect = true
                stopReading()
            }
        }
    }

    // 标签数据处理
    private suspend fun processTagData(tagCount: Int) {
        repeat(tagCount) {
            val tfs = myapp.Mreader.TAGINFO()
            val er = if (myapp.isquicklymode) {
                myapp.Mreader.AsyncGetNextTag(tfs)
            } else {
                myapp.Mreader.GetNextTag(tfs)
            }

            if (er == Reader.READER_ERR.MT_OK_ERR) {
                val tag = Reader.bytes_Hexstr(tfs.EpcId)
                val tagInfo = TagUtils.processTagInfo(tag, tfs, myapp.curnxpu8, myapp)

                processTagInfo(tagInfo)
                updateEantCount(tagInfo.tagInfo.AntennaID.toInt(), tag)

                if (myapp.VisStatics) {
                    updateStatistics(tag)
                }

                if (myapp.isFoundTag) {
                    updateTagSearch(tagInfo)
                }
            }
        }
    }

    // 更新标签搜索状态
    private suspend fun updateTagSearch(tagInfo: TagInfo) {
        lockObj.withLock {
            // 如果当前标签是正在搜索的标签
            if (tagInfo.epcstr.trim() == myapp.Curepc) {
                tagdisIsFound = true
                // 累加读取次数
                tagdisAllCount += tagInfo.tagInfo.ReadCnt
                // 累加RSSI值 (RSSI * 读取次数，用于计算平均值)
                tagdisAllRssi += tagInfo.tagInfo.RSSI * tagInfo.tagInfo.ReadCnt
            }
        }
    }

    // 处理标签搜索的声音反馈
    private suspend fun processTagSearchFeedback() {
        if (tagdisIsFound) {
            lockObj.withLock {
                // 计算平均RSSI值来决定声音反馈的频率
                val averageRssi = abs(tagdisAllRssi.toDouble() / tagdisAllCount)
                // RSSI值越小（越近）声音间隔越短
                val sleepTime = when {
                    averageRssi <= 25.0 -> 10L // 最小间隔
                    else -> ((averageRssi - 25) * 18).toLong() // 根据距离动态调整间隔
                }

                delay(sleepTime)
            }
            // 重置状态
            tagdisIsFound = false
            tagdisAllRssi = 0
            tagdisAllCount = 0
        }
    }

    private suspend fun processTagInfo(tagInfo: TagInfo) {
        lockTagsm.withLock {
            if (!_tagsMap.value!!.containsKey(tagInfo.key)) {
                handleNewTag(tagInfo)
            } else {
                updateExistingTag(tagInfo)
            }
        }
    }

    private fun handleNewTag(tagInfo: TagInfo) {
        _tagsMap.value = _tagsMap.value!!.toMutableMap().apply {
            put(tagInfo.key, tagInfo.tagInfo)
        }

        _totalCount.value = (_totalCount.value ?: 0) + 1

        val displayMap = createDisplayMap(tagInfo)
        _listMs.value = _listMs.value!!.toMutableList().apply {
            add(displayMap)
        }

        if (myapp.gpodemomode != 0) {
            handleGpoDemo(tagInfo.key)
        }
    }

    // GPO控制
    private fun handleGpoDemo(tagKey: String) = viewModelScope.launch {
        when (myapp.gpodemomode) {
            1 -> handleGpoMode1(tagKey)
            2 -> handleGpoMode2(tagKey)
            3, 4 -> handleGpoMode34(tagKey)
        }
    }

    private suspend fun handleGpoMode1(tagKey: String) {
        if (gpodemoauthortags.contains(tagKey)) {
            setGPOStates(true)
            delay(1000)
            setGPOStates(false)
        } else {
            repeat(3) {
                myapp.Mreader.SetGPO(1, 1)
                delay(20)
                myapp.Mreader.SetGPO(1, 0)
            }
        }
    }

    // 盘点模式设置
    fun selectInventoryMode(): Boolean {
        myapp.issmartmode = false
        return when (myapp.qmode) {
            0 -> { // 普通模式
                myapp.isquicklymode = false
                true
            }
            in 1..8 -> { // 快速模式系列
                configureQuickMode()
            }
            else -> false
        }
    }

    // U8标签模式切换
    private fun switchU8Mode() {
        val u8para = myapp.Mreader.NXP_U8_InventoryModePara()

        // 清除现有过滤器
        myapp.Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_TAG_FILTER, null)
        myapp.Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_TAG_EMBEDEDDATA, null)

        // 切换模式
        myapp.curnxpu8 = if (myapp.curnxpu8 == myapp.nxpu8) 0 else myapp.nxpu8

        when (myapp.curnxpu8) {
            0 -> configureU8Mode0()
            1 -> configureU8Mode1(u8para)
            2 -> configureU8Mode2(u8para)
            3 -> configureU8Mode3(u8para)
        }
    }

    // EPC排序功能
    fun sortByEpc() = viewModelScope.launch {
        lockTagsm.withLock {
            _listMs.value = _listMs.value!!.let { currentList ->
                listOf(currentList.first()) + currentList.drop(1).sortedBy { it["EPC ID"] }
            }
        }
    }

    // 停止读取
    fun stopReading() = viewModelScope.launch {
        isRun = false
        _readState.postValue(ReadState.Stopped)

        stopReadingProcess()
        generateReports()
        cleanupResources()
    }

    // 清除数据
    fun clearData() {
        _tagsMap.value = emptyMap()
        _listMs.value = emptyList()
        _totalCount.value = 0
        totalCountLast = 0
        vmaxStaticCount = 0
        _tagCount.value = 0
        resetCounters()
    }

    private fun resetCounters() {
        testCount = 0
        tagdisIsFound = false
        tagdisAllRssi = 0
        tagdisAllCount = 0
        vallcount = 0f
        valltime = 0L
    }

    // 暂停和恢复
    fun pauseReading() {
        handler?.removeCallbacksAndMessages(null)
    }

    fun resumeReading() {
        if (isRun && !myapp.issmartmode) {
            handler?.postDelayed(createReadingRunnable(), 0)
        }
    }

    override fun onCleared() {
        super.onCleared()
        readScope.cancel()
        dexel?.SaveandCloseExcelfile()
        handler?.removeCallbacksAndMessages(null)
    }

    private fun clearInternalStates() {
        _tagsMap.postValue(emptyMap())
        _listMs.postValue(emptyList())
        _totalCount.postValue(0)
        totalCountLast = 0
        vmaxStaticCount = 0
        testCount = 0
        tagdisIsFound = false
        tagdisAllRssi = 0
        tagdisAllCount = 0
        vallcount = 0f
        valltime = 0L
        vstaticStartTick = 0L
        vstaticTags.clear()
        _eantCount.postValue(emptyMap())
    }

    // 初始化天线计数
    private fun initializeAntCount() {
        _eantCount.postValue(
            myapp.Rparams.uants.associateWith { emptyList<String>() }
        )
    }

    // 初始化记录报表
    private fun initializeRecordReport() {
        try {
            dexel = DjxlExcel("时间数量报表").apply {
                CreatereExcelfile(
                    listOf(
                        "测试次数",
                        "标签次数",
                        "标签个数",
                        "新增个数",
                        "总数",
                        "时间(毫秒)"
                    )
                )
            }
        } catch (e: Exception) {
            _errorState.postValue("初始化报表失败: ${e.message}")
        }
    }

    // 初始化温度报表
    private fun initializeTemperatureReport() {
        try {
            dexel = DjxlExcel("电量温度报表").apply {
                val headers = listOf("时间", "温度", "电量%")
                val linestr = buildString {
                    append("${myapp.myhd.module}   ${Sub4TabActivity.nowpower} ")
                    append("${myapp.stoptimems / 60000}分钟记录一次")
                }
                CreatereExcelfile(linestr, headers)
            }
        } catch (e: Exception) {
            _errorState.postValue("初始化温度报表失败: ${e.message}")
        }
    }

    // 统计线程处理
    private fun launchStatisticsJob() = viewModelScope.launch {
        while (isRun) {
            val elapsedTime = System.currentTimeMillis() - startTick

            if (elapsedTime - vstaticStartTick > staticeveryt) {
                processStatistics(elapsedTime)
                vstaticStartTick = elapsedTime
            }

            delay(myapp.Rparams.sleep.toLong())

            // 检查是否需要停止
            checkStopConditions(elapsedTime)
        }
    }

    // 标签搜索线程
    private fun launchTagSearchJob() = viewModelScope.launch {
        while (isRun) {
            if (tagdisIsFound) {
                processTagSearch()
                tagdisIsFound = false
                tagdisAllRssi = 0
                tagdisAllCount = 0
            }
            delay(10)
        }
    }

    // 处理统计数据
    private suspend fun processStatistics(elapsedTime: Long) {
        if (elapsedTime > myapp.stoptimems) return

        lockObj.withLock {
            val tagCountUnit = vstaticTags.size
            val tagCount = _totalCount.value ?: 0
            val newTags = tagCount - totalCountLast
            totalCountLast = tagCount

            if (myapp.isReport_rec) {
                writeStatisticsToReport(
                    testCount + 1,
                    tagCountUnit,
                    newTags,
                    tagCount,
                    elapsedTime
                )
            }

            // 更新最大统计数
            if (tagCountUnit > vmaxStaticCount) {
                vmaxStaticCount = tagCountUnit
            }

            // 清理统计数据
            vstaticTags.clear()
        }
    }

    // 写入统计数据到报表
    private fun writeStatisticsToReport(
        testCount: Int,
        tagCountUnit: Int,
        newTags: Int,
        totalTags: Int,
        elapsedTime: Long
    ) {
        try {
            dexel?.WriteExcelfile(arrayOf(
                testCount,
                tagCountUnit,
                newTags,
                totalTags,
                elapsedTime
            ))
        } catch (e: Exception) {
            _errorState.postValue("写入报表失败: ${e.message}")
        }
    }

    // 处理标签搜索
    private suspend fun processTagSearch() {
        withContext(Dispatchers.IO) {
            lockObj.withLock {
                val dbv = abs(tagdisAllRssi) * 1.0 / tagdisAllCount
                val sleepTime = when {
                    dbv <= 25 -> 10L
                    else -> (dbv - 25) * 18
                }.toLong()
                delay(sleepTime)
            }
        }
    }

    // 更新天线计数
    private fun updateEantCount(antId: Int, tag: String) {
        _eantCount.value = _eantCount.value!!.toMutableMap().apply {
            val currentList = this[antId]?.toMutableList() ?: mutableListOf()
            if (!currentList.contains(tag)) {
                currentList.add(tag)
                put(antId, currentList)
            }
        }
    }

    // 检查停止条件
    private fun checkStopConditions(elapsedTime: Long) {
        if ((myapp.isstoptime && elapsedTime >= myapp.stoptimems) ||
            (myapp.isstopcount && (_totalCount.value ?: 0) >= myapp.stopcount)
        ) {
            testCount++

            if (myapp.VisTestFor && testCount < myapp.Vtestforcount) {
                handleTestForCycle()
            } else {
                isRun = false
            }
        }
    }

    // 处理测试循环
    private fun handleTestForCycle() = viewModelScope.launch {
        if (isdroppow) {
            handlePowerCycle()
        }

        delay(myapp.Vtestforsleep.toLong())

        if (isRun) {
            clearInternalStates()
            startTick = System.currentTimeMillis()
            restartReading()
        }
    }

    // 重新启动读取
    private suspend fun restartReading() {
        // 确保监听器已设置
        setupReaderListeners()
        try {
            when {
                myapp.ThreadMODE == 0 -> {
                    if (myapp.issmartmode) {
                        // 智能模式重启
                        val er = myapp.Mreader.AsyncStartReading_IT(
                            myapp.smartmode,
                            myapp.Rparams.uants,
                            myapp.Rparams.uants.size,
                            myapp.Rparams.option
                        )
                        if (er != Reader.READER_ERR.MT_OK_ERR) {
                            _errorState.postValue("重启读取失败: $er")
                            stopReading()
                            return
                        }
                    } else if (myapp.isquicklymode) {
                        // 快速模式重启
                        val er = myapp.Mreader.AsyncStartReading(
                            myapp.Rparams.uants,
                            myapp.Rparams.uants.size,
                            myapp.Rparams.option
                        )
                        if (er != Reader.READER_ERR.MT_OK_ERR) {
                            _errorState.postValue("重启读取失败: $er")
                            stopReading()
                            return
                        }
                    }
                    // 使用Handler重新开始读取循环
                    handler?.postDelayed(createReadingRunnable(), 0)
                }
                myapp.ThreadMODE == 1 -> {
                    // 事件模式重启
                    if (myapp.Mreader.StartReading(
                            myapp.Rparams.uants,
                            myapp.Rparams.uants.size,
                            myapp.m_BROption
                        ) != Reader.READER_ERR.MT_OK_ERR
                    ) {
                        _errorState.postValue("重启事件模式读取失败")
                        stopReading()
                        return
                    }
                }
            }

            startTick = System.currentTimeMillis()
            vstaticStartTick = System.currentTimeMillis() - startTick

        } catch (e: Exception) {
            _errorState.postValue("重启读取异常: ${e.message}")
            stopReading()
        }
    }

    // 创建读取Runnable
    private fun createReadingRunnable() = Runnable {
        viewModelScope.launch {
            val tagcnt = IntArray(1)

            val er = if (myapp.isquicklymode) {
                myapp.Mreader.AsyncGetTagCount(tagcnt)
            } else {
                myapp.Mreader.TagInventory_Raw(
                    myapp.Rparams.uants,
                    myapp.Rparams.uants.size,
                    myapp.Rparams.readtime.toShort(),
                    tagcnt
                )
            }

            processReadResult(er, tagcnt[0]) {
                // 声音回调
                // 注：实际声音播放应在Activity中处理
            }
        }
    }

    // 处理电源循环
    private suspend fun handlePowerCycle() {
        myapp.Mreader.CloseReader()
        myapp.Rpower.PowerDown()
        powstatus = false

        // 等待掉电完成
        while (powstatus) {
            delay(500)
        }

        // 重新上电
        myapp.Rpower.PowerUp()
        val er = myapp.Mreader.InitReader_Notype(myapp.Address, myapp.antportc)
        if (er == Reader.READER_ERR.MT_OK_ERR) {
            setupReaderListeners()
        }
    }

    // 创建显示Map
    private fun createDisplayMap(tagInfo: TagInfo): Map<String, String> = buildMap {
        put("Sort", (_totalCount.value ?: 0).toString())
        put(
            "EPC ID",
            if (myapp.isconngoods && myapp.listName.containsKey(tagInfo.epcstr.trim()))
                myapp.listName[tagInfo.epcstr.trim()] ?: tagInfo.epcstr
            else tagInfo.epcstr
        )
        put("Count", tagInfo.tagInfo.ReadCnt.toString())
        put("ANT", tagInfo.tagInfo.AntennaID.toString())
        put("Protocol", "")
        put("RSSI", tagInfo.tagInfo.RSSI.toString())
        put("Frequency", tagInfo.tagInfo.Frequency.toString())
        put("RFU", tagInfo.rfu)
        put("TimeStamp", tagInfo.tagInfo.TimeStamp.toString())
        put("TID", tagInfo.tid)
        put("BID", tagInfo.bid)
        if (myapp.curnxpu8 == 0) {
            put("Data", tagInfo.emdstr)
        }
    }

    private suspend fun handleError(er: Reader.READER_ERR) {
        myapp.Mreader.GetLastDetailError(myapp.ei)
        val errorMessage = "error:${er.value()} ${er}"
        _errorState.postValue(errorMessage)

        if (myapp.isquicklymode && er != Reader.READER_ERR.MT_OK_ERR) {
            if (er == Reader.READER_ERR.MT_HARDWARE_ALERT_ERR_BY_TOO_MANY_RESET) {
                myapp.needreconnect = true
                stopReading()
            }
        }
    }

    // 更新统计信息
    private suspend fun updateStatistics(tag: String) {
        lockObj.withLock {
            if (!vstaticTags.contains(tag)) {
                vstaticTags.add(tag)
            }
        }
    }

    // 更新已存在的标签
    private fun updateExistingTag(tagInfo: TagInfo) {
        _tagsMap.value = _tagsMap.value!!.toMutableMap().apply {
            val existing = this[tagInfo.key]
            existing?.apply {
                ReadCnt += tagInfo.tagInfo.ReadCnt
                RSSI = tagInfo.tagInfo.RSSI
                Frequency = tagInfo.tagInfo.Frequency
            }
            put(tagInfo.key, existing ?: tagInfo.tagInfo)
        }

        // 更新显示列表
        _listMs.value = _listMs.value!!.map { map ->
            if (map["EPC ID"] == tagInfo.epcstr) {
                map.toMutableMap().apply {
                    put("Count", tagInfo.tagInfo.ReadCnt.toString())
                    put("RSSI", tagInfo.tagInfo.RSSI.toString())
                    put("Frequency", tagInfo.tagInfo.Frequency.toString())
                    put("TimeStamp", tagInfo.tagInfo.TimeStamp.toString())
                    if (tagInfo.tid.isNotEmpty()) {
                        put("TID", tagInfo.tid)
                    }
                    if (tagInfo.bid.isNotEmpty()) {
                        put("BID", tagInfo.bid)
                    }
                }
            } else {
                map
            }
        }
    }

    // GPO模式2处理
    private suspend fun handleGpoMode2(tagKey: String) {
        if (gpodemoauthortags.contains(tagKey)) {
            myapp.Mreader.SetGPO(1, 1)
            delay(100)
            myapp.Mreader.SetGPO(1, 0)
        } else {
            myapp.Mreader.SetGPO(2, 1)
            delay(300)
            myapp.Mreader.SetGPO(2, 0)
        }
    }

    // GPO模式3和4处理
    private suspend fun handleGpoMode34(tagKey: String) {
        if ((myapp.gpodemomode == 3 && gpodemoauthortags.contains(tagKey)) ||
            (myapp.gpodemomode == 4 && !gpodemoauthortags.contains(tagKey))
        ) {
            triggerGPO()
        }
    }

    // GPO触发功能
    private suspend fun triggerGPO() {
        try {
            listOf(
                myapp.gpodemo1 to 1,
                myapp.gpodemo2 to 2,
                myapp.gpodemo3 to 3,
                myapp.gpodemo4 to 4
            ).forEach { (enabled, port) ->
                if (enabled) myapp.Mreader.SetGPO(port, 1)
            }

            delay(myapp.gpodemotime.toLong())

            listOf(
                myapp.gpodemo1 to 1,
                myapp.gpodemo2 to 2,
                myapp.gpodemo3 to 3,
                myapp.gpodemo4 to 4
            ).forEach { (enabled, port) ->
                if (enabled) myapp.Mreader.SetGPO(port, 0)
            }
        } catch (e: Exception) {
            _errorState.postValue("GPO触发失败: ${e.message}")
        }
    }

    // 设置GPO状态
    private fun setGPOStates(state: Boolean) {
        val value = if (state) 1 else 0
        listOf(
            myapp.gpodemo1 to 1,
            myapp.gpodemo2 to 2,
            myapp.gpodemo3 to 3,
            myapp.gpodemo4 to 4
        ).forEach { (enabled, port) ->
            if (enabled) myapp.Mreader.SetGPO(port, value)
        }
    }

    // 配置快速模式
    private fun configureQuickMode(): Boolean {
        return try {
            // 获取最大功率
            val mp = IntArray(1)
            val er = myapp.Mreader.ParamGet(Reader.Mtr_Param.MTR_PARAM_RF_MAXPOWER, mp)
            if (er != Reader.READER_ERR.MT_OK_ERR) return false

            // 配置天线功率
            configureAntennaPower(mp[0])

            // 配置特定模式参数
            when (myapp.qmode) {
                1 -> configureSingleTagMode()
                2 -> configureMultiTagMode()
                3 -> configureHandheldMode()
                4 -> configureSmartMode()
                5 -> configureE7TestMode()
                6 -> configureE7SmartModeV2()
                7 -> configureE7NewFastMode()
                8 -> configureE7SmartTempMode()
                else -> false
            }
        } catch (e: Exception) {
            _errorState.postValue("配置快速模式失败: ${e.message}")
            false
        }
    }

    // U8模式配置系列
    private fun configureU8Mode0() {
        if (myapp.nxpu8 == 1) {
            myapp.Mreader.EmbededData_ST().apply {
                accesspwd = null
                bank = 2
                startaddr = 0
                bytecnt = 12
            }.let {
                myapp.Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_TAG_EMBEDEDDATA, it)
            }
        }
    }

    private fun configureU8Mode1(u8para: Reader.NXP_U8_InventoryModePara) {
        myapp.Mreader.TagFilter_ST().apply {
            fdata = byteArrayOf(0x80.toByte())
            bank = 1
            flen = 1
            startaddr = 0x204
            isInvert = 0
        }.let {
            myapp.Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_TAG_FILTER, it)
        }

        myapp.Mreader.EmbededData_ST().apply {
            accesspwd = null
            bank = 2
            startaddr = 0
            bytecnt = 12
        }.let {
            myapp.Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_TAG_EMBEDEDDATA, it)
        }

        u8para.Mode[0] = 1
    }

    private fun configureU8Mode2(u8para: Reader.NXP_U8_InventoryModePara) {
        myapp.Mreader.TagFilter_ST().apply {
            fdata = byteArrayOf(0x80.toByte())
            bank = 1
            flen = 1
            startaddr = 0x203
            isInvert = 0
        }.let {
            myapp.Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_TAG_FILTER, it)
        }

        u8para.Mode[0] = 1
    }

    private fun configureU8Mode3(u8para: Reader.NXP_U8_InventoryModePara) {
        myapp.Mreader.TagFilter_ST().apply {
            fdata = byteArrayOf(0x80.toByte())
            bank = 1
            flen = 1
            startaddr = 0x204
            isInvert = 0
        }.let {
            myapp.Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_TAG_FILTER, it)
        }

        u8para.Mode[0] = 1
    }

    // 停止读取处理
    private suspend fun stopReadingProcess() {
        when (myapp.ThreadMODE) {
            0 -> {
                if (myapp.issmartmode) {
                    myapp.Mreader.AsyncStopReading_IT()
                } else if (myapp.isquicklymode) {
                    myapp.Mreader.AsyncStopReading()
                    checkPacketLoss()
                }
                handler?.removeCallbacksAndMessages(null)
            }
            1 -> {
                myapp.Mreader.StopReading()
            }
        }

        if (myapp.VisTestFor && testCount >= myapp.Vtestforcount) {
            isRun = false
        }
    }

    // 生成报表
    private suspend fun generateReports() {
        if (myapp.isReport_rec) {
            generateRecordReport()
        }
        if (myapp.isReport_tep) {
            generateTemperatureReport()
        }
        if (myapp.isReport_pos) {
            generatePositionReport()
        }
    }

    // 资源清理
    private fun cleanupResources() {
        handler?.removeCallbacksAndMessages(null)
        dexel?.SaveandCloseExcelfile()
        readScope.cancel()
    }

    // 帮助方法
    private fun checkPacketLoss() {
        val errdata = ByteArray(255)
        val er = myapp.Mreader.ParamGet(
            Reader.Mtr_Param.MTR_PARAM_READER_ERRORDATA,
            errdata
        )

        if (er == Reader.READER_ERR.MT_OK_ERR && errdata[0] == 2.toByte()) {
            val lostCount = ((errdata[1].toInt() and 0xff) shl 8) or (errdata[2].toInt() and 0xff)
            _errorState.postValue("LOST:$lostCount")
        }
    }

    private fun generateRecordReport() {
        if (testCount >= myapp.Vtestforcount) {
            val linestr = buildString {
                append("${myapp.myhd.module}   ${Sub4TabActivity.nowpower}")
                val avgCount = vallcount / maxOf(myapp.Vtestforcount, 1)
                val avgTime = valltime / maxOf(myapp.Vtestforcount, 1)
                append("  平均标签数量：$avgCount")
                append("\r\n平均耗时：$avgTime")
                append("  \r\n日期：${commfun.getcurDate()}")
                append("\r\n\r\n\r\n")
            }

            dexel?.mergeandtext(0, dexel?.GetY() ?: 0, 5, dexel?.GetY() ?: 0, linestr)
            vallcount = 0f
            valltime = 0L
        }
    }

    private suspend fun generateTemperatureReport() {
        val tempValue = IntArray(1)
        myapp.Mreader.ParamGet(
            Reader.Mtr_Param.MTR_PARAM_RF_TEMPERATURE,
            tempValue
        )

        dexel?.WriteExcelfile(arrayOf(
            commfun.getcurDate(),
            tempValue[0],
        ))
    }

    private fun generatePositionReport() {
        DjxlExcel("标签识读报表").apply {
            val tagList = _tagsMap.value!!.keys.map { it }
            CreateTestBoxExcelfile_v2(tagList)
        }
    }

    private fun configureAntennaPower(maxPower: Int) {
        myapp.Mreader.AntPowerConf().apply {
            antcnt = myapp.antportc
            for (i in 0 until antcnt) {
                Powers[i] = myapp.Mreader.AntPower().apply {
                    antid = i + 1
                    readPower = maxPower.toShort()
                    writePower = maxPower.toShort()
                }
            }
        }.let {
            myapp.Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_RF_ANTPOWER, it)
        }
    }

    // 单标签手持机模式
    private fun configureSingleTagMode(): Boolean {
        val er = myapp.Mreader.ParamSet(
            Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_SESSION,
            intArrayOf(0)
        )
        return if (er == Reader.READER_ERR.MT_OK_ERR) {
            myapp.Rparams.session = 0
            if (myapp.myhd.module == Module_Type.MODOULE_SLR1200) {
                myapp.Rparams.option = myapp.Rparams.option or 0x10
            }
            true
        } else {
            false
        }
    }

    // 多标签快速模式
    private fun configureMultiTagMode(): Boolean {
        val er = myapp.Mreader.ParamSet(
            Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_SESSION,
            intArrayOf(1)
        )
        return if (er == Reader.READER_ERR.MT_OK_ERR) {
            myapp.Rparams.session = 1
            true
        } else {
            false
        }
    }

    // 多标签手持机模式
    private fun configureHandheldMode(): Boolean {
        val er = myapp.Mreader.ParamSet(
            Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_SESSION,
            intArrayOf(1)
        )
        return if (er == Reader.READER_ERR.MT_OK_ERR) {
            myapp.Rparams.session = 1
            if (myapp.myhd.module == Module_Type.MODOULE_SLR1200) {
                myapp.Rparams.option = myapp.Rparams.option or 0x10
            }
            true
        } else {
            false
        }
    }

    // 多标签智能（控温）模式
    private fun configureSmartMode(): Boolean {
        val er = myapp.Mreader.ParamSet(
            Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_SESSION,
            intArrayOf(1)
        )
        return if (er == Reader.READER_ERR.MT_OK_ERR) {
            myapp.Rparams.session = 1
            myapp.smartmode = if (isE7Series()) {
                Reader.IT_MODE.IT_MODE_CT
            } else {
                if (myapp.myhd.module == Module_Type.MODOULE_SLR1200) {
                    myapp.Rparams.option = myapp.Rparams.option or 0x10
                }
                Reader.IT_MODE.IT_MODE_CT
            }
            myapp.issmartmode = true
            true
        } else {
            false
        }
    }

    // E7测试模式
    private fun configureE7TestMode(): Boolean {
        myapp.smartmode = Reader.IT_MODE.IT_MODE_E7v2
        myapp.issmartmode = true
        return true
    }

    // E7智能模式v2
    private fun configureE7SmartModeV2(): Boolean {
        myapp.Mreader.CustomParam_ST().apply {
            ParamName = "Reader/Ex10fastmode"
            ParamVal = ByteArray(22).apply {
                this[0] = 1  // 1表示启用，0表示不启用
                this[1] = 20
                for (i in 0..19) {
                    this[i + 2] = i.toByte()
                }
            }
        }.let {
            myapp.Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_CUSTOM, it)
        }
        return true
    }

    // E7新快速模式
    private fun configureE7NewFastMode(): Boolean {
        myapp.smartmode = Reader.IT_MODE.IT_MODE_E7CT
        myapp.issmartmode = true
        return true
    }

    // E7智能（控温）模式
    private fun configureE7SmartTempMode(): Boolean {
        myapp.smartmode = Reader.IT_MODE.IT_MODE_E7StopP
        myapp.issmartmode = true
        return true
    }

    // 辅助方法：检查是否为E7系列
    private fun isE7Series(): Boolean {
        return when (myapp.myhd.module) {
            Module_Type.MODOULE_SIM3100,
            Module_Type.MODOULE_SIM3200,
            Module_Type.MODOULE_SIM3300,
            Module_Type.MODOULE_SIM3400,
            Module_Type.MODOULE_SIM3500,
            Module_Type.MODOULE_SIM3600,
            Module_Type.MODOULE_SIM5100,
            Module_Type.MODOULE_SIM5200,
            Module_Type.MODOULE_SIM5300,
            Module_Type.MODOULE_SIM5400,
            Module_Type.MODOULE_SIM5500,
            Module_Type.MODOULE_SIM5600,
            Module_Type.MODOULE_SIM7100,
            Module_Type.MODOULE_SIM7200,
            Module_Type.MODOULE_SIM7300,
            Module_Type.MODOULE_SIM7400,
            Module_Type.MODOULE_SIM7500,
            Module_Type.MODOULE_SIM7600 -> true
            else -> false
        }
    }
}




